package image_cmds

import (
	"fmt"

	"atomgit.com/openlinksaas/devc/utils"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"github.com/spf13/cobra"
)

var existCmd = &cobra.Command{
	Use: "exist",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 1 {
			return fmt.Errorf("need param [image]")
		}
		return nil
	},
	RunE: runExist,
}

func runExist(cmd *cobra.Command, args []string) error {
	cli, err := client.NewClientWithOpts(client.FromEnv)
	if err != nil {
		return err
	}

	imgList, err := cli.ImageList(cmd.Context(), types.ImageListOptions{})
	if err != nil {
		return err
	}
	match := false
	for _, img := range imgList {
		for _, tag := range img.RepoTags {
			if tag == args[0] {
				match = true
			}
		}
		if match {
			break
		}
	}
	utils.PrintResult(match)
	return nil
}
